// pages/publish/addSteps/addStepNormal.js
const ui = require('../../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    upload_files: [],
    content: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('stepEditInfo', function(data) {
      if (data) {
        that.setData({
          content: data.content,
          upload_files: data.images
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //图片选择后
  afterRead(event) {
    var that = this;
    const { file } = event.detail;
    wx.uploadFile({
      url: 'https://shangjinxia.ltd/api/image/file',
      filePath: file.url,
      name: 'file',
      formData: {},
      success(res) {
        // 上传完成需要更新 upload_files
        var result = JSON.parse(res.data);
        const {
          upload_files = []
        } = that.data;
        upload_files.push({ ...file, url: file.thumb, upload_url: result.uploadFileUrl });
        that.setData({ upload_files });
      },
      fail() {
        ui.showToast('上传失败');
      }
    });
  },
  deleteImage(event) {
    const {
      upload_files = []
    } = this.data;
    upload_files.splice(event.detail.index);
    this.setData({
      upload_files
    });
  },
  actionSave(event) {
    if (event.detail.value.content.length == 0) {
      ui.showToast('请输入说明内容');
      return;
    }
    // var uploadList = [];
    // this.data.upload_files.forEach(element => {
    //   uploadList.push(element.upload_url)
    // });
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromStepNormal', {
      type: 'normal',
      content: event.detail.value.content,
      images: this.data.upload_files
    });
    wx.navigateBack();
  }
})